﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Xml;

namespace Vowei.Service.Excel
{
    public class DataConnection
    {
        private static readonly string _odcContentTemplate;
        private static XmlSerializerNamespaces _nsManager;

        static DataConnection()
        {
            _odcContentTemplate =
                "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns=\"http://www.w3.org/TR/REC-html40\">\r\n" +
                "<head>\r\n" +
                "<meta http-equiv=Content-Type content=\"text/x-ms-odc; charset=utf-8\">\r\n" +
                "<meta name=ProgId content=ODC.Table>\r\n" +
                "<meta name=SourceType content={0}>\r\n" +
                "<title>{1}</title>\r\n" +
                "<xml id=docprops>\r\n" +
                " <o:DocumentProperties xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns=\"http://www.w3.org/TR/REC-html40\">\r\n" +
                "  <o:Name>{1}</o:Name>\r\n" +
                " </o:DocumentProperties>\r\n" +
                "</xml>\r\n" +
                "<xml id=msodc>\r\n" +
                "{2}\r\n" +
                "</xml>\r\n" +
                "</head>\r\n" +
                "</html>";

            _nsManager = new XmlSerializerNamespaces();
            _nsManager.Add("odc", "urn:schemas-microsoft-com:office:odc");
        }

        public static string CreateOdcFile(OfficeDataConnection connection, string name)
        {
            if (connection == null)
                throw new ArgumentNullException("connection");

            var serializer = new XmlSerializer(connection.GetType());
            using (var stream = new MemoryStream())
            {
                serializer.Serialize(stream, connection, _nsManager);
                stream.Position = 0;
                using (var streamReader = new StreamReader(stream))
                {
                    var xml = streamReader.ReadToEnd();
                    
                    // 跳过生成的<?xml>标记
                    xml = xml.Substring(23);
                    return string.Format(_odcContentTemplate,
                        connection.Connection.Type, name, xml);
                }
            }
        }
    }
}
